﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace SimpleInfrastructure.Serialize
{
    public class ProtoBufSerializer:ISerializer
    {
        public dynamic Serialize(object o)
        {
            if (o == null)
            {
                return null;
            }
            using (MemoryStream memoryStream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize(memoryStream, o);
                byte[] objectDataAsStream = memoryStream.ToArray();
                return objectDataAsStream;
            }
        }

        public T Deserialize<T>(dynamic stream)
        {
            T result = default(T);
            try
            {
                using (MemoryStream memoryStream = new MemoryStream((byte[])stream))
                {
                    result = ProtoBuf.Serializer.Deserialize<T>(memoryStream);
                }
            }
            catch (Exception ex)
            {

            }
            return result;
        }

        public T Deserialize<T>(dynamic o, T notuse)
        {
            return Deserialize<T>(o);
        }
    }
}
